package com.hankarun.gevrek;

import java.util.ArrayList;
import java.util.List;

import com.hankarun.gevrek.lib.DataSource;
import com.hankarun.gevrek.lib.NewsGroupName;
import com.hankarun.gevrek.lib.ServerManager;

import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.ListView;
import android.widget.TextView;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;

public class GroupSelect extends Activity {

	private ListView grouplistview;
	private CustomAdapter adapter;
	protected ServerManager app;
	private List<String> selected;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_select);
        
        grouplistview = (ListView) findViewById(R.id.groupselectlistview);
        app = (ServerManager)getApplication();
        
        selected = new ArrayList<String>();
        
        ServerTask task = new ServerTask();
    	task.execute();
    	
    	EditText filterEditText = (EditText) findViewById(R.id.serchText);
    	filterEditText.addTextChangedListener(new TextWatcher() {
    		@Override
    	    public void onTextChanged(CharSequence s, int start, int before,
    	      int count) {
    	      adapter.getFilter().filter(s.toString());
    	    }
    	 
    	     @Override
    	     public void beforeTextChanged(CharSequence s, int start, int count,
    	      int after) {
    	     }

			@Override
			public void afterTextChanged(Editable arg0) {
				
			}
    	});
    	
    	grouplistview.setOnItemClickListener(new OnItemClickListener() {
    		@Override
    		public void onItemClick(AdapterView<?> parent, View view,
    			int position, long id) {
    			if(selected.contains(adapter.getItem(position)))
    				selected.remove(selected.indexOf(adapter.getItem(position)));
    			else
    				selected.add(adapter.getItem(position));
    			
    		}
    	});
    	
    	Button button = (Button) findViewById(R.id.finishselectButton);
    	button.setOnClickListener(new Button.OnClickListener() { 
        	public void onClick (View v){ 
	        		DataSource datasource = new DataSource(GroupSelect.this);
	            	datasource.open();
	            	datasource.dropGroups();
	            	for(String group : selected){
	            		datasource.createGroup(group);
	            	}
	            	datasource.close();
	            	setResult(1);
	            	finish();
        		}
        	});
    }

    
    private class ServerTask extends AsyncTask<Void, Void, List<String>> {
    	private ProgressDialog dialog;
    	@Override
    	protected void onPreExecute(){
    		dialog = ProgressDialog.show(GroupSelect.this, "", 
    				getString(R.string.downloadinggroups), true);
    	}
    	
    	@Override
    	protected void onPostExecute(List<String> s) {            	     
    		grouplistview.setTextFilterEnabled(true);
    		grouplistview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
            adapter = new CustomAdapter(GroupSelect.this, s);
            grouplistview.setAdapter(adapter);
            
            
        	DataSource datasource = new DataSource(GroupSelect.this);
        	datasource.open();
        	List<NewsGroupName> groupnames = datasource.getAllGroups();
        	for(NewsGroupName name : groupnames){
        		selected.add(name.getGroup());
        		for(int x=0; x < adapter.getCount(); x++){        			
        			if(adapter.getItem(x).equals(name.getGroup()))
        				grouplistview.setItemChecked(x, true);
        		}
        	}
        	datasource.close();
                                   
    	    dialog.dismiss();
    	}

    	@Override
    	protected List<String> doInBackground(Void... params) {	        
        	return app.listNewsGroups();
    	}

    }

    
    public class CustomAdapter extends ArrayAdapter<String> {
    	private final Context context;
    	private final List<String> values;
    	private Filter filter;
    	private List<String> filteredModelItemsArray;

    	public CustomAdapter(Context context, List<String> _values) {
    		super(context, android.R.layout.simple_list_item_multiple_choice, _values);
    		this.context = context;
    		values = new ArrayList<String>();
    		values.addAll(_values);

    		filteredModelItemsArray = new ArrayList<String>();
    		filteredModelItemsArray.addAll(_values);
    	}

    	@Override
    	public View getView(int position, View convertView, ViewGroup parent) {
    		LayoutInflater inflater = (LayoutInflater) context
    				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    		View rowView = inflater.inflate(android.R.layout.simple_list_item_multiple_choice, parent, false);
    		TextView textView = (TextView) rowView.findViewById(android.R.id.text1);

    		textView.setText(filteredModelItemsArray.get(position));
    		if(selected.contains(textView.getText().toString()))
    			grouplistview.setItemChecked(position, true);
    		else
    			grouplistview.setItemChecked(position, false);

    		return rowView;
    	}
    	
    	@Override
    	public Filter getFilter() {
    		if (filter == null){
    			filter = new CustomFilter();
    		}
    		return filter;
    	}
    	
    	private class CustomFilter extends Filter{

			@Override
			protected FilterResults performFiltering(CharSequence constraint) {
                constraint = constraint.toString().toLowerCase();
                FilterResults result = new FilterResults();
                if(constraint != null && constraint.toString().length() > 0)
                {
                    ArrayList<String> filteredItems = new ArrayList<String>();
                   
                    for(int i = 0, l = values.size(); i < l; i++)
                    {
                        String m = values.get(i);
                        if(m.contains(constraint))
                            filteredItems.add(m);
                    }
                    result.count = filteredItems.size();
                    result.values = filteredItems;
                }
                else
                {
                    synchronized(this)
                    {
                        result.values = values;
                        result.count = values.size();
                    }
                }
                return result;
			}

			@SuppressWarnings("unchecked")
			@Override
			protected void publishResults(CharSequence constraint,
					FilterResults results) {
                filteredModelItemsArray = (ArrayList<String>)results.values;
                notifyDataSetChanged();
                clear();
                for(int i = 0, l = filteredModelItemsArray.size(); i < l; i++)
                    add(filteredModelItemsArray.get(i));
                notifyDataSetInvalidated();
				
			}

    	}
    
    }

}
